import asyncio, pyautogui, random

from core.base_controller import BaseController
from core.utils import focus_wow

class KeyPressListController(BaseController):
    async def focus_wow(self):
        """ 定时任务 focus_wow """
        while True:
            # await self.ws_client.broadcast_log(message_content="focus_wow", message_type=1)
            focus_wow()
            try:
                await asyncio.sleep(random.uniform(5, 10))  # 任务可以被取消
            except asyncio.CancelledError:
                # await self.ws_client.broadcast_log(message_content="focus_wow 任务被取消", message_type=2)
                break  # 任务被取消后退出循环

    async def press_key(self, key, interval):
        """ 定时任务 press_key """
        while True:
            # await self.ws_client.broadcast_log(message_content=f"press_{key}", message_type=1)
            pyautogui.press(key)
            try:
                await asyncio.sleep(random.uniform(interval - 0.2, interval + 0.2))  # 任务可以被取消
            except asyncio.CancelledError:
                # await self.ws_client.broadcast_log(message_content=f"press_{key} 任务被取消", message_type=2)
                break  # 任务被取消后退出循环

    async def start(self, extra_data = {}):
        self.extra_data = extra_data
        await self.ws_client.broadcast_log(message_content=f"press_key start", message_type=1)
        """ 启动所有定时任务 """
        await self.stop_all_task()  # 停止之前所有任务
        
        # focus_task = asyncio.create_task(self.focus_wow())  # 创建任务
        # self.add_task(focus_task)  # 添加任务到列表
        key_list = self.extra_data.get("key_list", [])
        for item in key_list:
            task = asyncio.create_task(self.press_key(item.get("key"), item.get("interval")))  # 创建任务
            self.add_task(task)  # 添加任务到列表

    async def stop(self):
        """ 停止定时器 """
        await self.ws_client.broadcast_log(message_content=f"press_key stop", message_type=2)
        await self.stop_all_task()  # 停止所有任务